﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VelocityCMS.Domain;
using VelocityCMS.Models;
using System.Collections.Specialized;
using VelocityCMS.Components.VelocityComponents.Views;

namespace VelocityCMS.Controllers
{
    public class PageController : Controller
    {

        //TODO: Need to replace text with constants/enums or dictionary, how to handle?
        public void PageDisplay()
        {

            //TODO: Get The Page By its name this may not be the correct approach need to turn on / off page name for SEO
            PageDTO pageDTO = new PageDTO();
            IList<ComponentDTO> componentList = new List<ComponentDTO>();
            VelocityCMSDataContext dc = new VelocityCMSDataContext();
            IEnumerable<ContentGroup> cg = dc.LoadContent(Guid.Empty, Guid.Empty, null, null, "Page", GetPageNameFromURL(), Guid.Empty, null, null);

            //TODO: is count check needed, handle page not found
            if(cg.Count() > 0)
            {
                
                foreach (ContentElement pageContent in cg.First().ContentElements)
                {

                    if (pageContent.AssociatedGroupID != Guid.Empty)
                    {
                        //Guid? componentGroupID = pageContent.AssociatedContentID;
                        IEnumerable<ContentGroup> component = pageContent.AssociatedContentGroup; 
                        //IEnumerable<ContentGroup> component = dc.LoadContent(Guid.Empty, componentGroupID, Guid.Empty, null, null, null, Guid.Empty, null, null);     
                        ComponentDTO cdto = new ComponentDTO();
                        cdto.ContentData = component;
                        cdto.Name = component.First().GroupType;
                        componentList.Add(cdto);
                    }                    
                    
                    //TODO: Refactor into Page Rendering and Navigation Rendering
                    if (pageContent.ContentType == "PageTitle")
                    {
                        pageDTO.Page = pageContent.ContentData; 
                    }
              }

            }

            pageDTO.Components = componentList;
            RenderView("PageDisplay", pageDTO);
        }

        //TODO: Handle Errors
        public void PageSave()
        {
            if (ValidateComponent()){Save(Request.Form);}
            else{}
            PageDisplay();
        }

        private string GetPageNameFromURL()
        {
            IList<String> segments = HttpContext.Request.Url.Segments;
            String pagename = "";

            if (segments.Last() != "/" && segments.Last() != String.Empty)
            {
                pagename = segments.Last();
            }

            return pagename;
        }

        //TODO: Handle Dependant Transactions
        //TODO: Handle Validation Return Errors
        //Currently Each form posts back a field in this format fieldname_fieldID
        //At the moment this works, the only issue is Dependant Transactions.
        //For example, check if something already exists in the system before saving it.
        //TODO: Massive Save Instead of Save Each Element
        //Another note is multiple hits for every save in the system. I think this is the biggest issue of all at the moment
        private void Save(NameValueCollection formData)
        {
            VelocityCMSDataContext dc = new VelocityCMSDataContext();

            foreach (var field in formData)
            {
                if (field.ToString().Contains("ContentData_"))
                {
                    ContentElement contentElement = dc.ContentElements.Single(ce => ce.ID == new Guid(field.ToString().Substring(12)));  
                    contentElement.ContentData = formData.Get(field.ToString());
                    dc.SubmitChanges();
                }
            }
        }

        private bool ValidateComponent()
        {
            NameValueCollection formData = new NameValueCollection();
            formData = Request.Form;
            String componentName = formData.Get("ComponentName");
            IVelocityComponent component = (IVelocityComponent)Activator.CreateInstance(Type.GetType(componentName));
            return component.Validate();
        }
    }
}
